package com.wk.code.wkserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wk.code.wkserver.constant.NumberConstant;
import com.wk.code.wkserver.entity.Notify;
import com.wk.code.wkserver.entity.TechType;
import com.wk.code.wkserver.mapper.NotifyMapper;
import com.wk.code.wkserver.request.admin.NotifyRequest;
import com.wk.code.wkserver.response.base.PageInfo;
import com.wk.code.wkserver.service.INotifyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wq
 * @since 2021-08-15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class NotifyServiceImpl extends ServiceImpl<NotifyMapper, Notify> implements INotifyService {


    @Override
    public void add(NotifyRequest req) {
        if (StringUtils.isEmpty(req.getTitle())) {
            throw new RuntimeException("请输入标题");
        }
        Notify notify = new Notify();
        notify.setContent(req.getContent());
        notify.setTitle(req.getTitle());
        notify.setIdRead(NumberConstant.ZERO);
        save(notify);
    }

    @Override
    public void update(NotifyRequest req) {
        Notify notify = new Notify();
        BeanUtils.copyProperties(req, notify);
        updateById(notify);
    }

    @Override
    public void delete(Integer id) {
        baseMapper.deleteById(id);
    }

    @Override
    public Notify detail(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<Notify> page(NotifyRequest req) {
        IPage<Notify> page = new Page<>(req.getPageNumber(), req.getPageSize());
        LambdaQueryWrapper<Notify> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNoneEmpty(req.getContent())) {
            wrapper.like(Notify::getContent, req.getContent());
        }
        if (StringUtils.isNoneEmpty(req.getTitle())) {
            wrapper.like(Notify::getTitle, req.getTitle());
        }
        wrapper.orderByDesc(Notify::getCreateTime);
        List<Notify> records = baseMapper.selectPage(page, wrapper).getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            return new PageInfo<>(page.getTotal(), records);
        }
        return null;
    }

    @Override
    public List<String> getList() {
        return baseMapper.selectList(null).stream().map(Notify::getContent).collect(Collectors.toList());
    }
}
